package com.wl.login.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wl.bean.Result;
import com.wl.biz.BizException;
import com.wl.login.bean.LoginProperties;
import javax.servlet.http.HttpSession;

import com.wl.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("login")
public class LoginDo {
    @Autowired
    LoginProperties properties;

    private ObjectMapper objectMapper;

    @GetMapping("config")
    LoginProperties properties(){
        return properties;
    }

    JdbcTemplate jdbcTemplate;

    @RequestMapping("login")
    public Result login(String username, String password, HttpSession session) throws BizException {
        Utils.checkEmpty(username, "请输入用户名!");
        Utils.checkEmpty(password, "请输入密码");
        Utils.check(password.trim().length() < 3, "密码至少是3个字符");

        String sql = "select * from %s where %s=? and %s=?";
        sql = String.format(sql, properties.getUserTable(),
                properties.getUsernameColumn(),
                properties.getPasswordColumn());

        List list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(properties.getUserClassObject()),
                username, password);

        Utils.check(list.isEmpty(),"用户名或密码错误!");
        Utils.check(list.size()>1,"数据库设计问题!");
        Object user = list.get(0);

        session.setAttribute(properties.getSessionKey(), user);

        Map<String, Object> map = new HashMap<>();
        map.put("user", user);

        Object aGoto = session.getAttribute("goto");
        if (aGoto!=null) {
            map.put("goto", aGoto);
            session.removeAttribute("goto");
        }

        return new Result(1,"登录成功", map);
    }

    @RequestMapping("myinfo")
    Result myinfo(HttpSession session) throws BizException {
        Object myinfo = session.getAttribute(properties.getSessionKey());
        if(myinfo==null){
            throw new BizException("未登录");
        }
        return new Result(1, "已登录", myinfo);
    }

    @RequestMapping("logout")
    ModelAndView logout(ModelAndView modelAndView, HttpSession session) {
        session.invalidate();
        modelAndView.setViewName("redirect:/");
        return modelAndView;
    }

    @RequestMapping("getUsernameColumn")
    String getUsernameColumn(){
        return properties.getUsernameColumn();
    }

}

